<template>
  <my-add-form :columns="Table.columns" url="/projectMana/insert"></my-add-form>
  <madoka-s-table local-storage-key="project"
                  :value-setter="Table.valueSetter"
                  :editable="true"
                  :custom-edit-columns="Table.customEditColumns"
                  :scroll="{ y: -38, x: 1000 }"
                  :data-source="Table.dataSource" :columns="Table.columns">
    <template #operate="{cell}">
      <a @click="Modal.deploy(cell)">一键部署</a>
    </template>
    <template #localUrl="{ cell }">
      <a target="_blank" :href="cell.record.localUrl">{{ cell.record.localUrl }}</a>
    </template>
    <template #onlineUrl="{cell}">
      <a target="_blank" :href="cell.record.onlineUrl">{{ cell.record.onlineUrl }}</a>
    </template>
    <template #password="{cell}">
      ******
    </template>
    <template #type="{cell}">
      {{ Table.getType(cell) }}
    </template>
    <template #_cellEditor="{ cell }">
      <a-select v-model:value="cell.record.type" @change="v => {Table.change(v, cell)}">
        <a-select-option value="1">前端</a-select-option>
        <a-select-option value="2">后端</a-select-option>
      </a-select>
    </template>
  </madoka-s-table>
  <a-modal v-model:open="Modal.open" @ok="Modal.ok" :confirm-loading="Modal.confirm">
    <a-upload-dragger
      name="file"
      v-model:file-list="Modal.fileList"
      :showUploadList="false"
      directory
      :customRequest="Modal.upload"
    >
      <p class="ant-upload-drag-icon">
        <inbox-outlined></inbox-outlined>
        点击或拖拽到这里上传
      </p>
    </a-upload-dragger>
  </a-modal>
</template>
<script setup lang="ts">
import type { IColumn } from "@/types";
import { get, post } from "@/madoka/request";
import Fingerprint2 from "fingerprintjs2";
import { InboxOutlined } from "@ant-design/icons-vue";
import JSZip from "jszip";
import { message } from "ant-design-vue";
/*const s = window as any;
const user = {
  username: cell.record.username,
  password: cell.record.password
};
s.injection(user);
if (cell.record.type === "1") {

} else if (cell.record.type === "2") {

}*/
const Modal = (() => {
  const ok = async () => {
    s.confirm = true;
    const files = s.fileList.map((item) => item.originFileObj);
    const zip = new JSZip();

    // 将文件添加到压缩包
    files.forEach((file) => {
      zip.file(file.webkitRelativePath, file);
    });

    const blob = await zip.generateAsync({ type: "blob" });
    const chunkSize = 5 * 1024 * 1024; // 每片5MB
    const totalChunks = Math.ceil(blob.size / chunkSize);
    const keys = Object.keys(s.obj);

    // 循环上传每个分片
    for (let chunkIndex = 0; chunkIndex < totalChunks; chunkIndex++) {
      const start = chunkIndex * chunkSize;
      const end = Math.min(start + chunkSize, blob.size);
      const chunk = blob.slice(start, end);

      const formData = new FormData();
      formData.append('file', new File([chunk], `upload_part_${chunkIndex + 1}.zip`, { type: 'application/zip' }));

      // 添加其他参数
      keys.forEach((key) => {
        formData.append(key, s.obj[key] as string);
      });
      formData.append('chunkIndex', chunkIndex+'')
      formData.append('totalChunks', totalChunks+'')
      const res:any = await post("projectMana/deploy", formData, {
        headers: {
          "X-Fingerprint": Table.murmur,
          "Content-Type": "multipart/form-data",
        },
      });

      if (res.code !== 200) {
        message.error(`第 ${chunkIndex + 1} 片上传失败!`);
        s.confirm = false;
        return;
      }
    }

    message.success("所有片上传成功!");
    s.open = false;
    s.confirm = false;
  };

  const deploy = async (cell:any) => {
    Modal.open = true;
    const record = cell.record;
    s.obj = {
      filename: record.filename as string,
      serverIp: record.serverIp as string,
      deployPort: record.deployPort as string,
      identifier: record.identifier as string,
    };
  };

  const beforeUpload = async (file:any) => {
    // 处理上传前逻辑
  };

  const upload = (file:any) => {
    return true;
  };

  const s = reactive({
    fileList: [] as any[],
    confirm: false,
    obj: {} as any,
    open: false,
    deploy,
    beforeUpload,
    upload,
    ok,
  });

  return s;
})();

const Table = (() => {

  const getMurmur = async () => {
    Fingerprint2.get((components: any) => {
      const values = components.map((component: any, index: number) => {
        if (index === 0) { //把微信浏览器里UA的wifi或4G等网络替换成空,不然切换网络会ID不一样
          return component.value.replace(/\bNetType\/\w+\b/, "");
        }
        return component.value;
      });
      // 生成最终id murmur
      s.murmur = Fingerprint2.x64hash128(values.join(""), 31);
    });
  };
  const getList = async () => {
    const res = await get("/projectMana/list", {});
    s.dataSource = res.data;
  };
  const getType = (cell: any) => {
    const type = cell.record.type;
    if (type === "1") return "前端";
    if (type === "2") return "后端";
  };
  const change = async (v: any, cell: any) => {
    const id = cell.record.id;
    const ent = s.dataSource.find(item => item.id === id) as any;
    ent && (ent.type = v);
    await post("projectMana/update", { id: id, type: v });
  };
  const valueSetter = async (cell: any) => {
    const { record, newValue, column } = cell;
    if (record[column.dataIndex] !== newValue) {
      record[column.dataIndex] = newValue;
      //更新单元格
      await post("projectMana/update", { id: record.id, [column.dataIndex]: newValue });
    }
    return true;
  };
  const s = reactive({
    dataSource: <any[]>[],
    customEditColumns: ["type"],
    murmur: "",
    columns: <IColumn[]>[
      {
        dataIndex: "projectName",
        title: "项目名称"
      },
      {
        dataIndex: "filename",
        title: "文件名"
      },
      {
        dataIndex: "localUrl",
        title: "本地地址"
      },
      {
        dataIndex: "onlineUrl",
        title: "线上地址",
        autoHeight: true
      },
      {
        dataIndex: "username",
        title: "管理员账号用户名"
      },
      {
        dataIndex: "password",
        title: "管理员账号密码"
      },
      {
        dataIndex: "usernameAlias",
        title: "管理员用户名别名"
      },
      {
        dataIndex: "passwordAlias",
        title: "管理员密码别名"
      },
      {
        dataIndex: "identifier",
        title: "项目识别码"
      },
      {
        dataIndex: "type",
        title: "类型"
      },
      {
        dataIndex: "serverIp",
        title: "服务器Ip"
      },
      {
        dataIndex: "deployPort",
        title: "部署端口号"
      },
      {
        dataIndex: "operate",
        title: "操作"
      }
    ],
    valueSetter,
    getType,
    change
  });
  getList();
  getMurmur();
  return s;
})();


</script>


<style scoped>

</style>